package com.sunstar.cwcamerademo

import android.content.Context
import android.util.Log
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.*
import androidx.datastore.preferences.preferencesDataStore
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.runBlocking

const val TESTER_NAME = "CW_TESTER"

val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = TESTER_NAME)

object DSHelper {

    var appContext: Context? = null
    val dataStore: DataStore<Preferences>? by lazy {
        appContext?.dataStore
    }

    fun initContext(c: Context) {
        this.appContext = c;
    }

    suspend fun putData(name: String, any: Int) {
        Log.e("DSHelper", "getData:${dataStore} ")
        dataStore?.edit {
            it[intPreferencesKey(name)] = any
        }
    }

    suspend fun getData(name: String): Int {
        Log.e("DSHelper", "getData:${dataStore} ")
        var result = 0
        runBlocking {
            val data = dataStore?.data?.first {
                result = it[intPreferencesKey(name)] ?: 0
                true
            }
        }

        return result
    }

}